package org.adream.account.rest.api;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.adream.account.entity.UserEntity;
import org.adream.account.entity.UserVerifyEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.rest.api.model.Columns;
import org.adream.account.rest.api.model.DataTableRequest;
import org.adream.account.rest.api.model.DataTableResponse;
import org.adream.account.rest.api.model.UserVerifySearchForm;
import org.adream.account.service.ADreamServiceException;
import org.adream.account.service.UserService;
import org.adream.account.service.UserVerifyService;
import org.adream.account.util.Constant;
import org.adream.account.util.FileUtils;
import org.adream.account.util.SensorDataUtil;
import org.adream.account.util.UUIDUtil;
import org.adream.account.util.UserUtil;
import org.adream.account.util.Utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.sensorsdata.analytics.javasdk.SensorsAnalytics;
import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException;

/**
 * 身份认证  controller
 * @author sl
 *
 */
@Controller
@RequestMapping("/verify/")
public class UserVerifyApiController {
	
	private final static Logger logger = LoggerFactory.getLogger(UserVerifyApiController.class);
	
	@Autowired
	private UserVerifyService verifyService;
	
	@Value("${image.file.path.verifypic}")
	private String verifyPicPath;
	
	@Value("${file.path.resumefile}")
	private String resumeFilePath;
	
	@Value("${file.path.annuSurveyfile}")
	private String annuSurveyFilePath;
	
	@Value("${file.path.stufffile}")
	private String stuffFilePath;
	
	@Value("${file.path.createConCopyfile}")
	private String createConCopyFilePath;
	
	@Value("${file.path.excuteConCopyfile}")
	private String excuteConCopyFilePath;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SensorDataUtil sensorDataUtil;
	
	/**
	 * 新增用户认证信息
	 * @param verify
	 * @return
	 */
	@RequestMapping(value = "", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> addUserverify(@RequestBody UserVerifyEntity verify) {
		if(verify == null) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "新增Userverify失败,请求参数有误", null);
		}
		return verifyService.addUserVerify(verify);
	}
	
	/**
	 * 删除 逻辑删除
	 * @param uid  user id
	 * @param rleId role id
	 * @return
	 */
	@RequestMapping(value = "uid/{uid}/rleId/{rleId}", produces = "application/json;charset=UTF-8", method = RequestMethod.DELETE)
	@ResponseBody
	public ResultModel<?> deleteUserVerify(@PathVariable("uid") String uid,@PathVariable("rleId") String rleId) {
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(rleId)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "删除Userverify失败,请求参数有误", null);
		}
		return verifyService.deleteUserVerify(uid, rleId);
	}
	
	/**
	 * 根据删除标志查询
	 * @param dr 删除标志
	 * @return
	 */
	@RequestMapping(value = "dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryVerifiesByDr(@PathVariable("dr") Integer dr) {
		if(StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询UserVerify失败，请求参数有误", null);
		}
		List<UserVerifyEntity> verifies = verifyService.queryVerifiesByDr(dr);
		if(Utils.isEmptyCollection(verifies)) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);
		}
		return new ResultModel<List<UserVerifyEntity>>(ResultModel.SUCCESS, "根据删除标志查询dr成功", verifies);
	}
	
	/**
	 * 根据uid,删除标志查询
	 * @param uid user id
	 * @param dr 删除标志
	 * @return
	 */
	@RequestMapping(value = "uid/{uid}/dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryVerifiesByUidAndDr(@PathVariable("uid") String uid,@PathVariable("dr") Integer dr) {
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询UserVerify失败，请求参数有误", null);
		}
		List<UserVerifyEntity> verifies = verifyService.queryVerifiesByUidAndDr(uid, dr);
		if(Utils.isEmptyCollection(verifies)) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);
		}
		return new ResultModel<List<UserVerifyEntity>>(ResultModel.SUCCESS, "根据uid,删除标志查询成功", verifies);
	}
	
	/**
	 * 根据删除标志,当前uid查询
	 * @param dr  删除标志
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "dr/{dr}/uid", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryVerifiesByCurUidAndDr(@PathVariable("dr") Integer dr,
			HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败,请求参数为空", null);
		}
		List<UserVerifyEntity> verifies = verifyService.queryVerifiesByUidAndDr(uid, dr);
		if(Utils.isEmptyCollection(verifies)) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);
		}
		return new ResultModel<List<UserVerifyEntity>>(ResultModel.SUCCESS, "查询成功", verifies);
	}
	
	/**
	 * 根据rleId,删除标志查询
	 * @param rleId role id
	 * @param dr 删除标志
	 * @return
	 */
	@RequestMapping(value = "rleId/{rleId}/dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryVerifiesByRleIdAndDr(@PathVariable("rleId") String rleId,@PathVariable("dr") Integer dr) {
		if(StringUtils.isEmpty(rleId) || StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询UserVerify失败，请求参数有误", null);
		}
		List<UserVerifyEntity> verifies = verifyService.queryVerifiesByRleIdAndDr(rleId, dr);
		if(Utils.isEmptyCollection(verifies)) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);
		}
		return new ResultModel<List<UserVerifyEntity>>(ResultModel.SUCCESS, "根据rleId,删除标志查询成功", verifies);
	}
	
	/**
	 * 根据uid,rleId,删除标志查询
	 * @param uid user id
	 * @param rleId role id
	 * @param dr 删除标志
	 * @return
	 */
	@RequestMapping(value = "uid/{uid}/rleId/{rleId}/dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryVerifyByUidAndRleIdAndDr(@PathVariable("uid") String uid,@PathVariable("rleId") String rleId,@PathVariable("dr") Integer dr) {
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(rleId) || StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询UserVerify", null);
		}
		UserVerifyEntity verify = verifyService.queryVerifiesByUidAndRleIdAndDr(uid, rleId, dr);
		if(verify == null) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);
		}
		return new ResultModel<UserVerifyEntity>(ResultModel.SUCCESS, "根据uid,rleId,删除标志查询成功", verify);
	}
	
	/**
	 * 根据当前uid,角色id,删除标志查询
	 * @param rleId roleId
	 * @param dr  删除标志
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "uid/rleId/{rleId}/dr/{dr}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryByCurUidAndRleIdAndDr(@PathVariable("rleId") String rleId, @PathVariable("dr") Integer dr, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		if(StringUtils.isEmpty(uid) || StringUtils.isEmpty(rleId) || StringUtils.isEmpty(dr)) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询UserVerify参数为空", null);
		}
		UserVerifyEntity verify = verifyService.queryVerifiesByUidAndRleIdAndDr(uid, rleId, dr);
		if(verify == null) {
			//此处null 是 学生 教师 页面另外请求 获取 phone 和 email
			//如果当前认证不存在,将用户之前认证有关学校的信息查询出来便于反显
			ResultModel<?> resultModel = verifyService.queryRecentSchoolVerify(uid, dr);
			if(!ResultModel.SUCCESS.equals(resultModel.getReturnCode())) {
				return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);					
			} else {
				verify = new UserVerifyEntity();
				verify.setSchool(((UserVerifyEntity)resultModel.getReturnObject()).getSchool());
				return new ResultModel<UserVerifyEntity>(ResultModel.SUCCESS, "根据uid,删除标志查询最近认证信息成功", verify);
			}
		}
		//教师 学生 用户 email phone 另外获取 若有信息 不可更改
		switch(rleId) {
		case Constant.TEACHER_ROLE_ID: 
		case Constant.STUDENT_ROLE_ID:
			UserEntity userEntity = userService.queryUserByDrAndUid(1, verify.getUid());
			if(userEntity !=null) {
				if(!StringUtils.isEmpty(userEntity.getPhone())&&!StringUtils.isEmpty(userEntity.getPhone().trim())) {
					verify.setPhone(userEntity.getPhone());
				}
				if(!StringUtils.isEmpty(userEntity.getEmail())&&!StringUtils.isEmpty(userEntity.getEmail().trim())) {
					verify.setEmail(userEntity.getEmail());
				}
			}
			break;
		}
		
		if(!StringUtils.isEmpty(verify.getPhone()) && verify.getPhone().length() == Constant.ELEVEN) {
			verify.setPhone(Utils.replaceXing(verify.getPhone(), 3, 4));
		}
		if(!StringUtils.isEmpty(verify.getEmail())) {
			verify.setEmail(Utils.hideEmail(verify.getEmail()));
		}
		return new ResultModel<UserVerifyEntity>(ResultModel.SUCCESS, "根据uid,rleId,删除标志查询成功", verify);
	}
	
	/**
	 * 根据相关条件模糊查询 管理端 已弃用
	 * @param form  请求表单
	 * @return
	 */
	@RequestMapping(value = "queryVerifiesBySomeInfo", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> queryVerifiesBySomeInfo(@RequestBody UserVerifySearchForm form) {
		if(form == null || StringUtils.isEmpty(form.getDr())) {
			return new ResultModel<String>(ResultModel.ERR_PARAM, "查询失败,请求参数有误", null);
		}
		PageInfo<UserVerifyEntity> page = verifyService.queryVerifiesBySomeInfo(form.getUid(), form.getRealName(), form.getRleId(),
				form.getState(), form.getDr(),form.getPageNo(),form.getPageSize());
		if(page == null || Utils.isEmptyCollection(page.getList())) {
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "未查询到相应的UserVerify", null);
		}
		return new ResultModel<PageInfo<UserVerifyEntity>>(ResultModel.SUCCESS, "根据相关条件,查询成功", page);
	}
	
	/**
	 * 分页查询用户认证信息列表
	 * @param dp
	 * @return
	 */
	@RequestMapping(value = "queryVerifiesByDataTable", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public DataTableResponse<UserVerifyEntity> queryVerifiesByDataTable(@RequestBody DataTableRequest dp) {
		int pageSize = dp.getLength();
		int currPage = dp.getStart();
		logger.info("查询订单...");
		if (pageSize <= 0) {
			pageSize = 10;
		}
		if (currPage <= 0) {
			currPage = 1;
		}else{
			currPage = currPage/pageSize + 1;
		}
		String where = "";
		List<Columns> columns = dp.getColumns();
		for(Columns c:columns){
			if(StringUtils.isEmpty(c.getName()) || StringUtils.isEmpty(c.getSearch().getValue())){
				continue;
			}else{
				String name=c.getName();
				switch(name){
				case "rleName":
					if(!StringUtil.isEmpty(c.getSearch().getValue())){
						where += " and ( t.realName like CONCAT('%','"+ c.getSearch().getValue() +"','%') or u_v.uid like CONCAT('%','"+ c.getSearch().getValue() +"','%')  "
								+ "or u.phone = '"+ c.getSearch().getValue() +"' )";
					}
					break;
				default:
				}
			}
		}
		
		where += "and u_v.dr = 1 AND rle.dr = 1";
		
		dp.setExtendsWhere(where); 
		
		PageInfo<UserVerifyEntity> pif = verifyService.queryVerifiesByDataTable(dp);
		DataTableResponse<UserVerifyEntity> dtr = new DataTableResponse<UserVerifyEntity>();
		dtr.setData(pif.getList());
		dtr.setDraw(dp.getDraw());
		dtr.setRecordsFiltered(pif.getTotal());
		dtr.setRecordsFiltered(pif.getTotal());
		return dtr;
		 
	}
	
	/**
	 * "身份认证"后台管理审核"身份认证"
	 * @param verifyEntity
	 * @return
	 */
	@RequestMapping(value = "checkVerifyAndSynData", produces = "application/json;charset=UTF-8", consumes = "multipart/form-data", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> checkVerifyAndSynData(UserVerifyEntity verifyEntity) {
		logger.debug("审核'身份认证'");
		return verifyService.checkVerifyAndSynData(null,verifyEntity.getUid(),verifyEntity.getRleId(), verifyEntity);
	}
	
	/**
	 * 新增/更新前端认证
	 * @param verify
	 * @param pic	认证图片
	 * @param resumeFile	简历
	 * @param annuSurveyFile	年检报告
	 * @param stuffFile		认证材料
	 * @param createConCopyFile	设立合同扫描件
	 * @param excuteConCopyFile	执行合同扫描件
	 * @return
	 */
	@RequestMapping(value = "saveOrUpdateVerify", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel<?> updateFrontVerify(UserVerifyEntity verify,
			@RequestPart(value = "pic", required = false) MultipartFile pic,
			@RequestPart(value = "resumeFile", required = false) MultipartFile resumeFile,
			@RequestPart(value = "annuSurveyFile", required = false) MultipartFile annuSurveyFile,
			@RequestPart(value = "stuffFile", required = false) MultipartFile stuffFile,
			@RequestPart(value = "createConCopyFile", required = false) MultipartFile createConCopyFile,
			@RequestPart(value = "excuteConCopyFile", required = false) MultipartFile excuteConCopyFile,
			HttpServletRequest request) {
		try {
			if(verify == null) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "新增失败,请求参数有误", null);
			}
			String uid = UserUtil.getUidByRequest(request);
			
			//校长训练营合法性校验
			if(!StringUtils.isEmpty(verify.getRleId())
					&&"htc".equals(verify.getRleId().toLowerCase())
					&& (StringUtils.isEmpty(verify.getUid()) || !verify.getUid().equals(uid))
					) {
				return new ResultModel<String>(ResultModel.ERR_PERMISSION, "对不起，当前认证链接不合规", null);
			}
			
			verify.setUid(uid);
			if(StringUtils.isEmpty(verify.getUid()) || StringUtils.isEmpty(verify.getRleId()) || StringUtils.isEmpty(verify.getSort())) {
				return new ResultModel<String>(ResultModel.ERR_PARAM, "新增失败,请求参数有误", null);
			}
			
			//rleId为undefined 
			//rleId 为 去远方id  = goFarAway 
			//rleId 为 教练计划id  = coachPaln 
			if(Constant.UNDEFINED.equals(verify.getRleId().toLowerCase())
					||"gofaraway".equals(verify.getRleId().toLowerCase())  	//去远方
					||"coachplan".equals(verify.getRleId().toLowerCase()) //教练计划
					||"htc".equals(verify.getRleId().toLowerCase())  //校长训练营
					||"adreamcenter".equals(verify.getRleId().toLowerCase())  //社区
					) {
				//通过认证角色排序值获取认证角色id
				verify.setRleId(Utils.getVerifyRleIdBySort(verify.getSort()));
			}
			// 4种去远方ID校验  认证成功的不允许修改
			//  认证失败的或者审核中的 不同relId 删除原来的
			//  放入service中校验
			 
			//神策数据'盒子_用户身份认证'事件埋点
			SensorsAnalytics sa = null;
			try {
				sa = sensorDataUtil.getSensorsAnalytics();
			} catch (IOException e) {
				logger.warn("更新失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073,请联系管理员", null);
			}
			Map<String, Object> properties = new HashMap<>();
			properties.put("certification_type", Utils.getAuthName(verify.getSort()) + "认证");
			properties.put("identity_id", verify.getRleId());
			properties.put("is_success", false);
			
			//后台数据长度验证
			if(!StringUtils.isEmpty(verify.getSubject()) && verify.getSubject().length() > Constant.COMMON_DATA_LENGTH) {
				properties.put("failure_reason", "所交科目输入太长");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-2,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "所交科目输入太长,请精简", null);
			}
			
			if(!StringUtils.isEmpty(verify.getCompany()) && verify.getCompany().length() > Constant.COMMON_DATA_LENGTH) {
				properties.put("failure_reason", "机构/单位输入太长");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-3,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "机构/单位输入太长,请精简", null);
			}
			
			if(verify.getEduAge() != null && verify.getEduAge() > 100) {
				properties.put("failure_reason", "教龄不合法");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-4,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "请输入合法的教龄", null);
			}
			
			if(!StringUtils.isEmpty(verify.getCreCode()) && verify.getCreCode().length() > Constant.COMMON_DATA_LENGTH) {
				properties.put("failure_reason", "统一社会信用代码输入太长");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-5,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "统一社会信用代码输入太长,请精简", null);
			}
			
			if(!StringUtils.isEmpty(verify.getJob()) && verify.getJob().length() > Constant.COMMON_DATA_LENGTH) {
				properties.put("failure_reason", "职业输入太长");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-6,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "职业输入太长,请精简", null);
			}
			
			if(!StringUtils.isEmpty(verify.getIntro()) && verify.getIntro().length() > Constant.INTRO_MAX_LENGTH) {
				properties.put("failure_reason", "简介输入太长");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-7,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "简介输入太长,请精简", null);
			}
			
			if(!StringUtils.isEmpty(verify.getWechat()) && verify.getWechat().length() > Constant.COMMON_DATA_LENGTH) {
				properties.put("failure_reason", "微信输入太长");
				try {
					sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
					sa.flush();
				} catch (InvalidArgumentException e) {
					logger.warn("更新失败," + e.getMessage());
					return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-8,请联系管理员", null);
				}
				return new ResultModel<String>(ResultModel.WARN_DATA_LENGTH, "微信输入太长,请精简", null);
			}
			
			if(pic != null && pic.getSize() != Constant.ZERO) {
				String path = verifyPicPath.endsWith(File.separator) ? verifyPicPath : verifyPicPath + File.separator;
				String oriFileName = pic.getOriginalFilename();
				String ext = oriFileName.substring(oriFileName.lastIndexOf(".") + 1);
				String fileName = Utils.parseDateToYearMonthDay(new Date()) + "-" + UUIDUtil.createUUID() + "." + ext;
				verify.setCrePic(fileName);
				fileName = path + fileName;
				FileUtils.writeToFile(new File(fileName), pic.getInputStream());
			}
			
			//法人简历
			if(resumeFile != null && resumeFile.getSize() != Constant.ZERO) {
				String[] fileName = Utils.getFileName(resumeFile, resumeFilePath);
				if(StringUtils.isEmpty(fileName)) {
					properties.put("failure_reason", "法人简历上传失败");
					try {
						sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
						sa.flush();
					} catch (InvalidArgumentException e) {
						logger.warn("更新失败," + e.getMessage());
						return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-9,请联系管理员", null);
					}
					return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败:法人简历上传失败", null);
				}
				verify.setResume(fileName[1]);
				//上传法人简历
				FileUtils.writeToFile(new File(fileName[0] + fileName[1]), resumeFile.getInputStream());
			}
			
			//年检报告
			if(annuSurveyFile != null && annuSurveyFile.getSize() != Constant.ZERO) {
				String[] fileName = Utils.getFileName(annuSurveyFile, annuSurveyFilePath);
				if(StringUtils.isEmpty(fileName)) {
					properties.put("failure_reason", "年检报告上传失败");
					try {
						sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
						sa.flush();
					} catch (InvalidArgumentException e) {
						logger.warn("更新失败," + e.getMessage());
						return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-10,请联系管理员", null);
					}
					return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败:年检报告上传失败", null);
				}
				verify.setAnnuSurvey(fileName[1]);
				//上传年检报告
				FileUtils.writeToFile(new File(fileName[0] + fileName[1]), annuSurveyFile.getInputStream());
			}
			
			//认证材料
			if(stuffFile != null && stuffFile.getSize() != Constant.ZERO) {
				String[] fileName = Utils.getFileName(stuffFile, stuffFilePath);
				if(StringUtils.isEmpty(fileName)) {
					properties.put("failure_reason", "认证材料上传失败");
					try {
						sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
						sa.flush();
					} catch (InvalidArgumentException e) {
						logger.warn("更新失败," + e.getMessage());
						return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-11,请联系管理员", null);
					}
					return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败:认证材料上传失败", null);
				}
				verify.setStuff(fileName[1]);
				//上传认证材料
				FileUtils.writeToFile(new File(fileName[0] + fileName[1]), stuffFile.getInputStream());
			}
			
			//设立合同扫描件
			if(createConCopyFile != null && createConCopyFile.getSize() != Constant.ZERO) {
				String[] fileName = Utils.getFileName(createConCopyFile, createConCopyFilePath);
				if(StringUtils.isEmpty(fileName)) {
					properties.put("failure_reason", "设立合同扫描件上传失败");
					try {
						sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
						sa.flush();
					} catch (InvalidArgumentException e) {
						logger.warn("更新失败," + e.getMessage());
						return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-12,请联系管理员", null);
					}
					return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败:设立合同扫描件上传失败", null);
				}
				verify.setCreateConCopy(fileName[1]);
				//上传设立合同扫描件
				FileUtils.writeToFile(new File(fileName[0] + fileName[1]), createConCopyFile.getInputStream());
			}
			
			//执行合同扫描件
			if(excuteConCopyFile != null && excuteConCopyFile.getSize() != Constant.ZERO) {
				String[] fileName = Utils.getFileName(excuteConCopyFile, excuteConCopyFilePath);
				if(StringUtils.isEmpty(fileName)) {
					properties.put("failure_reason", "执行合同扫描件上传失败");
					try {
						sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
						sa.flush();
					} catch (InvalidArgumentException e) {
						logger.warn("更新失败," + e.getMessage());
						return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误01073-13,请联系管理员", null);
					}
					return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败:执行合同扫描件上传失败", null);
				}
				verify.setExcuteConCopy(fileName[1]);
				//上传执行合同扫描件
				FileUtils.writeToFile(new File(fileName[0] + fileName[1]), excuteConCopyFile.getInputStream());
			}
			ResultModel<?> resultModel = verifyService.saveOrUpdateVerify(verify.getUid(),verify.getRleId(),verify);
			if(ResultModel.SUCCESS.equals(resultModel.getReturnCode())) {
				properties.put("is_success", true);
				properties.put("failure_reason", "");
			} else {
				properties.put("is_success", false);
				properties.put("failure_reason", resultModel.getReturnMessage());
			}
			try {
				sa.track(uid, true, Constant.SENSOR_DATA_ADREAMBOX_IDENTITY_AUDIT, properties);
				sa.flush();
			} catch (InvalidArgumentException e) {
				logger.warn("更新失败," + e.getMessage());
				return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误0107-5,请联系管理员", null);
			}
			return resultModel;
		} catch (IOException e) {
			logger.warn("上传认证图片失败:)");
			return new ResultModel<String>(ResultModel.ERR_PARAM, "操作失败:上传认证图片失败", null);
		}
	}
	
	/**
	 * 查询当前用户最近的"身份认证"
	 * @param dr	删除标志
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryRecentVerifyByCurUidAndDr", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResultModel<?> queryRecentVerifyByCurUidAndDr(@RequestParam("dr") Integer dr, HttpServletRequest request) {
		String uid = UserUtil.getUidByRequest(request);
		return verifyService.queryRecentVerify(uid, dr);
	}
	
	
	/**
	 * 
	 * @param rleId  必填
	 * @param state  n时为空 ，其他为状态值
	 * @param where  n时为空，其他为搜索条件
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException 
	 */
	@RequestMapping(value = "downloadExcel/{rleId}/{state}/{where}", produces = "application/json;charset=UTF-8" ,method = RequestMethod.GET)
	@ResponseBody
	public void download(@PathVariable("rleId") String rleId,@PathVariable("state") String state,@PathVariable("where") String where,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		if(StringUtils.isEmpty(state)||"n".equals(state.trim().toLowerCase())) {
			state = null;
		}
		if(StringUtils.isEmpty(where)||"n".equals(where.trim().toLowerCase())) {
			where = null;
		}
		String title = "";
		switch (rleId) {
		case Constant.COACH_PLAN_A_ID:
			title = "社会志愿者";
			break;
		case Constant.COACH_PLAN_B_ID:
			title = "学生志愿者";
			break;
		case Constant.COACH_PLAN_C_ID:
			title = "梦想领队";
			break;
		case Constant.COACH_PLAN_D_ID:
			title = "梦想讲师";
			break;
		case Constant.TEACHER_ROLE_ID:
			title = "梦想教师";
			break;
		default:
			title = "尚未开发 ...";
			break;
		}
		HSSFWorkbook workbook = verifyService.createWorkBookByState(rleId,state,where,title);
		
		if(workbook == null) {
			return;
		}
		try {
			
		
        String filename =  java.net.URLEncoder.encode("（" + title + "）身份认证.xls", "UTF-8");
        
        response.setContentType("application/vnd.ms-excel");  
        response.setHeader("Content-disposition", "attachment;filename=" + filename);  
        OutputStream ouputStream = response.getOutputStream();  
        workbook.write(ouputStream);  
        ouputStream.flush();  
        ouputStream.close();  
		} catch (Exception e) {
			logger.error("身份认证导出 error");
		}
	}
	
	
	
}